import QtQuick 2.0
import Sailfish.Silica 1.0
import Sailfish.WebView 1.0
import Sailfish.WebEngine 1.0

import "../../components"
import "./LoginDiscord.js" as Js

Dialog {

    WebView {
        id: webView1
        anchors.fill: parent
        privateMode: true
        url: "https://discord.com/login"
        httpUserAgent : "Mozilla/5.0 (Android 8.1.0; Mobile; rv:78.0) Gecko/78.0 Firefox/78.0"
        viewportHeight: parent.height

        onViewInitialized: {
            // Подключение слушателя событий
            webView1.loadFrameScript(Qt.resolvedUrl("./../../framescript.js"));
            webView1.addMessageListener("webview:action")
        }

        onRecvAsyncMessage: {
            switch (message) {
                case "webview:action":
                    // Получение асинхронных ответов
                    try {
                        console.log("Data webview:action=" + JSON.stringify(data))

                        if (data.token) {
                            window.client.__TOKEN = data.token
                        }
                    } catch(e) {
                        console.log("Error webview:action=" + e.toString())
                    }
                    break
            }
        }

        Component.onCompleted: {
            // Отключение CORS
            WebEngineSettings.setPreference("security.disable_cors_checks", true, WebEngineSettings.BoolPref)

            Js.WebViewReady()
        }

        Component.onDestruction: Js.WebViewDestroyed()
    }
}
